/* 
 * 抽奖程序服务.
 */


import { Response, Request } from "restify";

import { getCustomRepository } from "typeorm";

import "reflect-metadata";

import { MemberEntity } from "../entity/MemberEntity";
import { BingoEntity } from "../entity/BingoEntity";
import { PrizeEntity } from "../entity/PrizeEntity";
import { WinnerEntity } from "../entity/WinnerEntity";

import { BingoRepository } from "../repository/BingoRepository";
import { BlackRepository } from "../repository/BlackRepository";
import { MemberRepository } from "../repository/MemberRepository";
import { PrizeRepository } from "../repository/PrizeRepository";
import { WinnerRepository } from "../repository/WinnerRepository";

const https = require('https');


let bingoRepository : BingoRepository;
let blackRepository : BlackRepository;
let memberRepository : MemberRepository;
let prizeRepository : PrizeRepository;
let winnerRepository : WinnerRepository

export class RestResource {

    //private bingoRepository : BingoRepository;
    //private memberRepository : MemberRepository;
    //private prizeRepository : PrizeRepository;
    //private winnerRepository : WinnerRepository

    constructor() {
        bingoRepository = getCustomRepository(BingoRepository);
        blackRepository = getCustomRepository(BlackRepository);
        memberRepository = getCustomRepository(MemberRepository);
        prizeRepository = getCustomRepository(PrizeRepository);
        winnerRepository = getCustomRepository(WinnerRepository);
	}

	/**
	 * /bingo/current
	 */
	getCurrentBingo(req: Request, res: Response, next: Function) {

		bingoRepository.findByCurrent(true)
			.then(result=>{
				res.send(result);
			});
		
		next();
	}

    getPrizesByBingo(req: Request, res: Response, next: Function) {

        prizeRepository.queryByBingo(req.params['bingo'])
            .then(result=>{
                res.send(result);
            });

        next();
    }



    getAllMembers(req: Request, res: Response, next: Function) {

        memberRepository.queryAll()
            .then(result=>{
                res.send(result);
            });

        next();
    }

    getMembersWithoutWinner(req: Request, res: Response, next: Function) {

        memberRepository.queryByValidWithoutWinner(true, req.params['bingo'])
            .then(result=>{
                res.send(result);
            });

        next();
    }

    getMembersWithoutWinnerAndBlack(req: Request, res: Response, next: Function) {

        memberRepository.queryByValidWithoutWinnerAndBlack(true, req.params['bingo'], req.params['prize'])
            .then(result=>{
                res.send(result);
            });

        next();
    }






    getBlacksByBingoPrize(req: Request, res: Response, next: Function) {

        blackRepository.queryByBingoPrize(req.params['bingo'], req.params['prize'])
            .then(result=>{
                res.send(result);
            });

        next();
    }


    /*  /winner/:bingo  */
    getWinnersByBingo(req: Request, res: Response, next: Function) {

        winnerRepository.queryByBingo(req.params['bingo'])
            .then(result=>{
                res.send(result);
            });

        next();
	}

    getWinnersByPrize(req: Request, res: Response, next: Function) {

        winnerRepository.queryByPrize(req.params['bingo'], req.params['prize'])
            .then(result=>{
                res.send(result);
            });

        next();
    }


    removeWinnerById(req: Request, res: Response, next: Function) {

        console.log(req.params['winner']);

        winnerRepository.deleteById(req.params['winner'])
           .then(result => {
               console.log(result);
           });

        next();
    }


    addWinnerByRandom(req: Request, res: Response, next: Function) {

        //console.log(http);

        //let r = this.random(1, 100);
        //console.log("随机数" + r);




        memberRepository.queryByValidWithoutWinnerAndBlack(true, req.params['bingo'], req.params['prize'])

            .then(result => {

                console.log("参与总数:" + result.length);

                let r = Math.floor(Math.random() * result.length);

                console.log("中奖序号:" + result[r].code + "|" + result[r].name);

                //let m = result[r];
                let w = new WinnerEntity();

                //w.id = m.id;
                w.member = result[r];
                w.prize = new PrizeEntity();
                w.prize.bid = req.params['bingo'];
                w.prize.pid = req.params['prize'];

                winnerRepository.add(w);
w
                res.send(w);
            });

        next();
    }


    /**
     * 生成一个从min到max之间的随机数
     */
    random(min: number, max: number) {

        https.get({
            host: "www.random.org",
            port: 443,
            path: "/integers/?format=plain&num=1&min=1&max=100&col=1&base=10",
            agent: false
        }, (response) => {
            //console.log(response.readAsText());

            console.log("生成随机数...");

            let rawData = '';
            response.on('data', (chunk) => { rawData += chunk; });
            response.on('end', () => {
                let r = parseInt(rawData);

                return r;
            });
        }).on('error', (e) => {
            console.error("访问远程失败...");

            let r = Math.floor(Math.random() * (max - min)) + min;

            return r;
        });

    }


}
